Skip to content

Styling In React

React is unopinionated when it comes to styling. As a result, there are dozens of options out there when it comes to pairing CSS with React.

Technically, there's nothing stopping you from doing things the “traditional” way. You could keep a bunch of CSS files, and include them with <link> tags in your index.html.

But honestly, if you want to have the best experience building with React, there are better approaches.

Remember when we first talked about components, and we saw this graphic?

A graph showing 3 colored pillars for HTML, CSS, and JS. Another graph shows 3 gradient pillars, mixing the technologies, but organized into components (Button, Datepicker, Modal, etc)

The core idea with components is that each component is a bundle of markup (in JSX), logic (in JS), and styles (in CSS). Our Button component should “own” all the styles related to that component!

When we structure our code this way, something magical happens. Working with CSS becomes so much simpler.

Let's talk about it.

Video Summary

  • The traditional way of writing CSS involves writing lots of different selectors to target the same element. This leads to an "arms race", where every selector needs to be more and more aggressive, in order to override existing styles
  • This has long been a frustration of writing CSS on large projects, and there have been many proposed solutions. One of the most popular is BEM (Block Element Modifier), a naming methodology.
  • BEM does make CSS much easier to work with if it's followed 100% of the time. Unfortunately, human nature means that it's very easy to go off the rails, especially when it comes to large projects with many developers. It requires superhuman discipline to follow the methodology.
  • When React grew to prominence, the community realized that there was an opportunity to improve things. In the years since, there have been many many different tools released, including styled-components, emotion, vanilla-extract, stitches, etc.
  • These tools "bake in" the scoping, generating unique selectors for us automatically.
  • We'll see a concrete example in the next lesson.